package vip.finance.makemoney.controller;

import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import vip.finance.makemoney.common.WebJson;
import vip.finance.makemoney.common.vo.LoginReq;
import vip.finance.makemoney.common.vo.LoginRes;
import vip.finance.makemoney.common.vo.UserInfo;
import vip.finance.makemoney.config.annotation.NoAuth;
import vip.finance.makemoney.config.exception.BusinessException;
import vip.finance.makemoney.entity.User;
import vip.finance.makemoney.service.IUserService;

/**
 * @author yangbin
 * @since 2023-01-19
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    @Resource
    private IUserService userService;

    //登录
    @NoAuth
    @PostMapping("/login")
    private WebJson<LoginRes> login(@RequestBody LoginReq body) {
        UserInfo userInfo = userService.login(body.getAccount(), body.getPassword());
        LoginRes loginRes = new LoginRes();
        loginRes.setToken(userInfo.getToken());
        return WebJson.success(loginRes);
    }

    //注册
    @NoAuth
    @PostMapping("/register")
    private WebJson<LoginRes> register(@RequestBody LoginReq body) {
        if (userService.count(Wrappers.<User>lambdaQuery().eq(User::getUsername, body.getAccount())) > 0) {
            throw new BusinessException("用户已存在");
        }
        User user = new User();
        user.setUsername(body.getAccount());
        user.setName(body.getAccount());
        user.setPassword(SecureUtil.md5(body.getPassword()));
        userService.save(user);
        return WebJson.success(login(body));
    }

    //退出登录
    @PostMapping("/outLogin")
    private WebJson<LoginRes> outLogin() {
        return WebJson.success();
    }

    //登录信息
    @GetMapping("/user-info")
    private WebJson<UserInfo> userInfo() {
        UserInfo currentUser = currentUser();
        //脱敏防止泄露信息
        currentUser.getCookieList().forEach(
                x -> {
                    x.setAccountId(DesensitizedUtil.bankCard(x.getAccountId()));
                    x.setCookie(DesensitizedUtil.password(x.getCookie()));
                    x.setValidatekey(DesensitizedUtil.password(x.getValidatekey()));
                }
        );
        return WebJson.success(currentUser);
    }
}
